<template>
  <view class="flex-col">

    <view :class="boole?'bottom115':''">
      <!--基础信息-->
      <basic-info v-model="detailForm" :boole="boole" ref="refBasicInfo"/>

      <!--出险信息-->
      <be-danger-info v-model="detailForm" :boole="boole" ref="refbeDangerInfo"/>

      <!--主车定损-->
      <master-car v-model="detailForm" :boole="boole" :options="options"
                  :depreciationList="depreciationList"
                  ref="refMasterCar"/>

      <!--三者定损-->
      <view class="item-wrap" style="margin-bottom: 0">
        <view class="lineBottom10">
          <uni-section title="保险公司定损额（三者）" type="line"/>
        </view>

        <view style="margin: 8rpx 20rpx 30rpx 20rpx">
          <uni-forms ref="detailForm" :model="detailForm" :label-position="boole ? 'top' : 'left'"
                     labelWidth="auto">

            <view v-for="(item,index) in detailForm.threeLossAssessmentDtoList" :key="index">

              <view style="display: flex;justify-content: flex-start;align-items: center;margin-bottom: 20rpx"
                    v-if="detailForm.threeLossAssessmentDtoList.length > 1 && boole">
                <text>{{ `保险公司定损额(三者)表${index + 1}` }}</text>
                <button class="uni-button"
                        size="mini" @click="delThreeLoss(item, index )" type="warn">删除
                </button>
              </view>

              <uni-forms-item label="三者车牌号:" :key="index"
                              v-if="requiredTable(detailForm.accidentType)"
                              :required="true"
                              :name="'threeLossAssessmentDtoList.'+index+'.otherCarNo'"
                              :rules="[{required: true, errorMessage: '请输入三者车牌号'}]">
                <text :class="'otherCarNo'+index"/>
                <uni-easyinput v-if="boole" v-model="item.otherCarNo"
                               placeholder="请输入三者车牌号"/>
                <text v-else> {{ item.otherCarNo || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="三者车牌号:" v-else>
                <uni-easyinput v-if="boole" v-model="item.otherCarNo"
                               placeholder="请输入三者车牌号"/>
                <text v-else> {{ item.otherCarNo || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="三者定损金额:" :key="index"
                              v-if="requiredTable(detailForm.accidentType)"
                              :required="true"
                              :name="'threeLossAssessmentDtoList.'+index+'.otherAssessmentPrice'"
                              :rules="[{required: true, errorMessage: '请输入三者定损金额'}]">
                <text :class="'otherAssessmentPrice'+index"/>
                <uni-easyinput v-if="boole"
                               :value="handleOtherAssessmentPrice(detailForm.threeLossAssessmentDtoList[index],index)"
                               disabled
                               placeholder="请输入三者定损金额"/>
                <text v-else> {{ item.otherAssessmentPrice || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="三者定损金额:" v-else>
                <uni-easyinput v-if="boole" v-model="item.otherAssessmentPrice"
                               @blur="blurTable( item,'otherAssessmentPrice')"
                               :value="handleOtherAssessmentPrice(detailForm.threeLossAssessmentDtoList[index],index)"
                               disabled
                               placeholder="请输入三者定损金额"/>
                <text v-else> {{ item.otherAssessmentPrice || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="人伤金额:" :key="index"
                              v-if="requiredTable(detailForm.accidentType)"
                              :required="true"
                              :name="'threeLossAssessmentDtoList.'+index+'.personPrice'"
                              :rules="[{required: true, errorMessage: '请输入人伤金额'}]">
                <text :class="'personPrice'+index"/>
                <uni-easyinput v-if="boole" v-model="item.personPrice"
                               @clear="clear(item,'personPrice')"
                               @blur="blurTable( item,'personPrice')"
                               placeholder="请输入人伤金额"/>
                <text v-else> {{ item.personPrice || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="人伤金额:" v-else>
                <uni-easyinput v-if="boole" v-model="item.personPrice"
                               @clear="clear(item,'personPrice')"
                               @blur="blurTable( item,'personPrice')"
                               placeholder="请输入人伤金额"/>
                <text v-else> {{ item.personPrice || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="施救费用:" :key="index"
                              v-if="requiredTable(detailForm.accidentType)"
                              :required="true"
                              :name="'threeLossAssessmentDtoList.'+index+'.rescueCost'"
                              :rules="[{required: true, errorMessage: '请输入施救费用'}]">
                <text :class="'rescueCost'+index"/>
                <uni-easyinput v-if="boole" v-model="item.rescueCost"
                               @clear="clear(item,'rescueCost')"
                               @blur="blurTable( item,'rescueCost')"
                               placeholder="请输入施救费用"/>
                <text v-else> {{ item.rescueCost || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="施救费用:" v-else>
                <uni-easyinput v-if="boole" v-model="item.rescueCost"
                               @clear="clear(item,'rescueCost')"
                               @blur="blurTable( item,'rescueCost')"
                               placeholder="请输入施救费用"/>
                <text v-else> {{ item.rescueCost || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="物损金额:" :key="index"
                              v-if="requiredTable(detailForm.accidentType)"
                              :required="true"
                              :name="'threeLossAssessmentDtoList.'+index+'.damagePrice'"
                              :rules="[{required: true, errorMessage: '请输入物损金额'}]">
                <text :class="'damagePrice'+index"/>
                <uni-easyinput v-if="boole" v-model="item.damagePrice"
                               @clear="clear(item,'damagePrice')"
                               @blur="blurTable( item,'damagePrice')"
                               placeholder="请输入物损金额"/>
                <text v-else> {{ item.damagePrice || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="物损金额:" v-else>
                <uni-easyinput v-if="boole" v-model="item.damagePrice"
                               @clear="clear(item,'damagePrice')"
                               @blur="blurTable( item,'damagePrice')"
                               placeholder="请输入物损金额"/>
                <text v-else> {{ item.damagePrice || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="其他:" :key="index">
                <uni-easyinput v-if="boole" v-model="item.threeOther"
                               @clear="clear(item,'threeOther')"
                               @blur="blurTable( item,'threeOther')"
                               placeholder="请输入其他"/>
                <text v-else> {{ item.threeOther || '-' }}</text>
              </uni-forms-item>

            </view>

            <uni-forms-item label="上传附件:">
              <image-common :disabled="!boole" :up-type="2" v-model="detailForm.threeLossAssessmentUrl"/>
            </uni-forms-item>


            <view style="display: flex;justify-content: center;align-items: center;" v-if=" boole">
              <button class="uni-button add-button" size="mini" type="primary" @click="addThreeLoss">
                添加
              </button>
            </view>

          </uni-forms>
        </view>
      </view>

      <!-- 其他费用 -->
      <other-expenses v-model="detailForm" :boole="boole"/>

      <!--出险相关信息-->
      <related-info v-model="detailForm" :boole="boole" ref="refRelatedInfo"/>

      <!--收取加速折旧费-->
      <accelerated v-model="detailForm" :depreciationList="depreciationList" :boole="boole"/>

      <!--用印文件-->
      <printed-document v-model="detailForm" v-if="Number(detailForm.settlementType) === 1" :boole="boole"/>

      <!--理赔款支付（其他费用）-->
      <view class="item-wrap" style="margin-bottom: 0" v-if="Number(detailForm.settlementType) === 2">
        <view class="lineBottom10">
          <uni-section title="理赔款支付（其他费用）" type="line"/>
        </view>

        <view style="margin: 8rpx 20rpx 30rpx 20rpx">
          <uni-forms ref="detailForm" :model="detailForm" :label-position="boole ? 'top' : 'left'" labelWidth="auto">

            <uni-forms-item label="合计总费用:">
              <uni-easyinput v-if="boole" v-model="detailForm.compensationPaymentTotalAmount"
                             disabled
                             placeholder="请输入合计总费用"/>
              <text v-else> {{ detailForm.compensationPaymentTotalAmount || '-' }}</text>
            </uni-forms-item>

            <view v-for="(item,index) in detailForm.compensationPaymentDto" :key="index">

              <view style="display: flex;justify-content: flex-start;align-items: center;margin-bottom: 20rpx"
                    v-if="boole">
                <text>{{ `理赔款支付表${index + 1}` }}</text>
                <button class="uni-button"
                        size="mini" @click="delDecoration(item, index )" type="warn">删除
                </button>
              </view>

              <uni-forms-item label="收款方:" required="boole" :name="`compensationPaymentDto.${index}.payee`"
                              :rules="[{required: true, errorMessage: '请输入收款方'}]">
                <uni-easyinput v-if="boole" v-model="item.payee"
                               placeholder="请输入收款方"/>
                <text v-else> {{ item.payee || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="收款费用:">
                <uni-easyinput v-if="boole" v-model="item.payAmount"
                               @clear="clear(item,'payAmount')"
                               @blur="blurTable( item,'payAmount')"
                               placeholder="请输入收款费用"/>
                <text v-else> {{ item.payAmount || 0 }}</text>
              </uni-forms-item>

              <uni-forms-item label="收账号:">
                <uni-easyinput v-if="boole" v-model="item.collectionAccount"
                               placeholder="请输入收账号"/>
                <text v-else> {{ item.collectionAccount || '-' }}</text>
              </uni-forms-item>

            </view>

            <view style="display: flex;justify-content: center;align-items: center;" v-if="boole">
              <button
                  class="uni-button add-button" size="mini" type="primary" @click="addDecoration">
                添加
              </button>
            </view>

          </uni-forms>
        </view>
      </view>

    </view>
    <!--审批流程-->
    <!--    <exam-flow v-if="flowId" :instanceId="flowId"/>-->

    <view class="button-container" v-if="boole">
      <button class="btn-item" @click="submit">提 交</button>
    </view>

  </view>
</template>

<script>

import {
  getSettlementDetails,
  getAddSettlementDetails,
  getAddSettlementList,
} from "@/api/insuranceSettlement";
import {getInsuranceSelectList, getList} from "@/api/maintain/maintainList";
import {toNumberAdd} from "@/pages/quota/libs/utils.js";
import basicInfo from "./components/basicInfo.vue";
import beDangerInfo from "./components/beDangerInfo.vue";
import masterCar from "./components/masterCar.vue"
import otherExpenses from "./components/otherExpenses.vue"
import relatedInfo from "./components/relatedInfo.vue"
import accelerated from "./components/accelerated.vue"; //收取加速折旧费
import printedDocument from "./components/printedDocument.vue"; //用印文件
export default {
  name: "add",
  components: {
    basicInfo,
    beDangerInfo,
    masterCar,
    otherExpenses,
    relatedInfo,
    accelerated,
    printedDocument,
  },
  computed: {
    requiredTable() {
      return function (sgVal) {
        let bool = false;
        if (Number(sgVal) === 2 && this.boole) {
          bool = true;
        } else {
          bool = false;
        }
        return bool;
      };
    },

  },
  watch: {},
  data() {
    return {
      detailForm: {
        //基础信息
        carNo: "",
        vinNo: "",
        modelName: "",
        seriesName: "",
        brandName: "",
        propertyRightName: "",
        registerTime: "",
        customerName: "",
        syxPolicyCode: "",
        jqxPolicyCode: "",
        accidentTime: "",
        carId: 0,

        //出险信息
        settlementType: "1",
        insuredName: "",
        driverName: "",
        responsibilityType: "",
        responsibleInsuranceUnitName: "",
        accidentType: "",
        accidentLocation: "",
        humanInjury: "",
        reportingCaseTime: "",
        reportingCaseNum: '',
        leaseStartTime: '',
        leaseEndTime: '',

        //主车定损
        vehicleAssessmentPrice: "",
        persionAssessmentPrice: "",
        otherAssessmentPrice: "",
        assessmentTotalPrice: "",
        dangerMaintenanceShop: "",
        accidentPhotos: "",
        lossAssessmentOss: "",
        maintenanceShop: '',
        maintenanceShopId: '',

        //三者定损
        threeLossAssessmentDtoList: [],
        threeLossAssessmentUrl: '',

        //其他费用
        otherPrice: "",
        otherCostReason: "",
        otherCostUrl: "",

        //出险相关信息
        advancePayment: "",
        advancePaymentCost: '',
        assessmentRemark: "",
        outDangerRemark: "",

        //收取加速折旧费
        depreciationPlan: "",
        depreciationPlanId: "",
        depreciationPrice: "",

        //用印文件

        //理赔款支付（其他费用）
        compensationPaymentTotalAmount: '',
        compensationPaymentDto: [
          {
            payee: "",//收款方
            payAmount: "",//   收款费用
            collectionAccount: "", //收账号
          }
        ],

        //印章信息
        attachmentUrl: "",
        useSealsOss: ''

      },
      boole: false,
      flowId: null,
      options: [],
      depreciationList: []
    };
  },
  onLoad(op) {
    let title = "";
    if (op?.type === "edit") {
      this.handleAddCarNo(op)
      title = "保险理赔申请";
      this.boole = true;
    }
    if (op?.type === "view") {
      this.handleDetail(op?.id)
      title = "保险理赔详情";
      this.boole = false;
    }
    this.detailForm.carId = op?.carId;
    uni.setNavigationBarTitle({
      title,
    });
  },
  mounted() {
    this.handleList();
    this.handleDepreciationPlan()
  },
  methods: {
    handleDepreciationPlan() {
      getList().then((res) => {
        if (res.code === 200) {
          this.depreciationList = res.data || [];
        }
      });
    },

    handleList() {
      getInsuranceSelectList({businessTypeCode: "4"}).then((res) => {
        if (res.code === 200) {
          this.options = res.data;
        }
      });
    },

    //获取详情
    async handleDetail(id) {
      try {
        const res = await getSettlementDetails(id);
        this.detailForm = res.data || {}
        this.detailForm.reportingCaseNum = res.data?.reportingCaseNum || ''
      } catch (e) {
        console.log(e)
      }
    },

    //通过车牌获取新增数据
    handleAddCarNo(op) {
      this.loading = true;
      try {
        getAddSettlementDetails(op?.carNo).then(res => {
          if (res.code === 200) {
            let val = res.data[0]
            this.detailForm.carNo = val.carNo
            this.detailForm.vinNo = val.vinNo
            this.detailForm.modelName = val.modelName
            this.detailForm.seriesName = val.seriesName
            this.detailForm.brandName = val.brandName
            this.detailForm.propertyRightName = val.propertyRightName
            this.detailForm.carId = val.carId
            this.detailForm.customerName = val.customerName
            this.detailForm.registerTime = val.registerTime
            this.detailForm.ascription = val.ascription
            this.detailForm.operationsName = val.operationsName
            this.detailForm.region = val.region
            this.detailForm.leaseStartTime = val.leaseStartTime
            this.detailForm.leaseEndTime = val.leaseEndTime

            this.detailForm.jqxPolicyCode = op?.jqxPolicyCode
            this.detailForm.syxPolicyCode = op?.syxPolicyCode
            this.detailForm.accidentTime = op?.accidentTime
            this.detailForm.insuredName = op?.insuredName
            console.log(op)
          }
        })
      } catch (e) {
      } finally {
        this.loading = false;
      }
    },

    handleOtherAssessmentPrice(val, index) {
      if (!val) return 0
      let num = 0;
      let a = toNumberAdd(Number(val?.damagePrice || 0), Number(val?.personPrice || 0))
      let b = toNumberAdd(Number(val?.rescueCost || 0), Number(val?.threeOther || 0))
      num = toNumberAdd(a, b)
      this.$set(
          this.detailForm.threeLossAssessmentDtoList[index],
          "otherAssessmentPrice",
          num
      );
      return num;
    },

    addThreeLoss() {
      let obj = {
        personPrice: "",
        rescueCost: "",
        damagePrice: "",
        otherAssessmentPrice: "",
        otherCarNo: "",
        threeOther: "",
      };
      this.detailForm.threeLossAssessmentDtoList.push(obj);
    },

    delThreeLoss(row, key) {
      this.detailForm.threeLossAssessmentDtoList.splice(key, 1);
    },

    blurTable(row, field) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      if (row[field]) {
        if (msg.test(Number(row[field]))) {
          if (Number(row[field]) >= 0) {
            let _value = row[field].toString().match(/^\d+(?:\.\d{0,2})?/)[0];
            row[field] = _value;
          } else {
            row[field] = "";
          }
        } else {
          row[field] = "";
        }
      }
      this.handleCount()
    },

    clear(row, field) {
      row[field] = ''
      this.handleCount()
    },

    addDecoration() {
      let obj = {
        payee: "",
        payAmount: "",
        collectionAccount: "",
      }
      this.detailForm.compensationPaymentDto.push(obj)
    },

    delDecoration(row, key) {
      this.detailForm.compensationPaymentDto.splice(key, 1);
    },

    handleCount() {
      let arr = this.detailForm.compensationPaymentDto;
      let totalCents = 0;

      for (let i = 0; i < arr.length; i++) {
        totalCents += Math.round(Number(arr[i].payAmount) * 100);
      }

      this.detailForm.compensationPaymentTotalAmount = (totalCents / 100).toFixed(2);
    },


    async submit() {
      try {

        let effectPromises = [
          this.$refs.refbeDangerInfo?.handleEffect() || [], //出险信息
          this.$refs.refMasterCar?.handleEffect() || [], //主车定损
          this.$refs.refMasterCar?.handleEffect() || [], //主车定损
          this.handleEffect(), //保险公司定损额（三者）
          this.$refs.refRelatedInfo?.handleEffect() || [], //出险相关信息
        ];

        // 等待所有效果处理完成
        await Promise.all(effectPromises);

        // 显示加载状态
        uni.showLoading();

        // 发送维护请求
        const res = await getAddSettlementList(this.detailForm);

        if (res.code === 200) {
          uni.$emit("refBackList", true);
          this.$modal.msgSuccess("提交成功");
          let url = `/pages/CarPage/insuranceSettlement/list`
          setTimeout(() => {
            uni.navigateBack({
              delta: 2
            })
            //this.$tab.redirectTo(url);
          }, 1000);
        }
      } catch (error) {
        if (typeof error === 'string') {
          this.$nextTick(() => {
            uni.pageScrollTo({
              selector: error,
            });
          });
        } else {
          console.error(error)
        }
      } finally {
        setTimeout(() => {
          uni.hideLoading();
        })

      }
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.detailForm.validate().then(res => {
          resolve();
        }).catch(err => {
          reject('.maintainProjectUrl');
        })
      });
    },
  },
};
</script>

<style scoped lang="scss">
.add-button {
  margin-left: 20rpx;
}
</style>


